package com.tencent.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.tencent.entity.OrderSetting;
import com.tencent.entity.Result;
import com.tencent.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Fame
 * @date: 2022-08-16 10:04
 * @description:
 */
@RestController
@RequestMapping("orderSetting1")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    @GetMapping("/{yearMonth}")
    public Result getByMonth(@PathVariable String yearMonth){
        String startDay = yearMonth + "-1";
        String endDay = yearMonth + "-31";


        List<OrderSetting> orderSettings = orderSettingService.findByOrderDate(startDay, endDay);

        return Result.success(orderSettings);
    }

    @RequestMapping("/addOne")
    public int addOrder(OrderSetting orderSetting){
        return orderSettingService.insert(orderSetting);
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile ) throws IOException {
        if (excelFile != null){
            // 获取表格数据的数据流
            InputStream is = excelFile.getInputStream();

            List<OrderSetting> orderSettings = new ArrayList<>(35);
            EasyExcel.read(is,OrderSetting.class,new SyncReadListener(){
                @Override
                public void invoke(Object object, AnalysisContext context) {
                    orderSettings.add((OrderSetting) object);
                }
            }).doReadAll();

            //批处理
            if (null != orderSettings){
                orderSettings.forEach(orderSetting -> orderSettingService.insert(orderSetting));
            }
        }
        return Result.success(null);
    }
}
